
public class ThreadController {

	int availableDatabaseCertificates[];                   
	int poolSize;                          
	int maxPoolSize;  

	public ThreadController(int maxSize) {

		this.maxPoolSize = maxSize;   
		poolSize         = 0;             

		availableDatabaseCertificates = new int[maxSize];
		for(int i=0; i < maxSize; i++) {
			availableDatabaseCertificates[i] = -1;        
		}
	}
	public synchronized int getPassCertificate() {

		while (poolSize == maxPoolSize) {

			try {
				wait();
			} catch (InterruptedException e) {}
		}

		int certificate = findFreeCertificate();
		if (certificate == -1) {
			System.out.println("Bug: could not find free ticket when we should be able to.");
		}
		availableDatabaseCertificates[certificate] = certificate;  
		poolSize++;                        

		return certificate;
	}
	public synchronized void returnCertificate(int certificate)
			throws IllegalArgumentException {

		if (poolSize == 0) {
			throw new IllegalArgumentException("Error");
		}

		if (availableDatabaseCertificates[certificate] != certificate) {
			throw new IllegalArgumentException("Error");
		}

		availableDatabaseCertificates[certificate] = -1; 
		poolSize--;

		notifyAll(); 
	}
	protected int findFreeCertificate() {

		for(int i=0; i < maxPoolSize; i++) {
			if (availableDatabaseCertificates[i] == -1) {
				return i;
			}
		}
		return -1;
	}
}
